package inet.app.controller.connect;

import inet.app.model.util.Util;

import java.io.IOException;
import java.io.DataInputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

import org.json.JSONObject;

public class MasterConnector {
	private String _masterHost = "";
	private int _masterPort;
	private Socket _socket;
	private boolean isConnected = false;
	protected PrintStream _outToSlave;
	protected DataInputStream _inFromSlave;

	public Socket getSocket() {
		return _socket;
	}

	public void setSocket(Socket socket) {
		this._socket = socket;
	}

	public MasterConnector() {

	}

	public MasterConnector(String address, int port) {
		_masterHost = address;
		_masterPort = port;
		try {
			this._socket = new Socket(_masterHost, _masterPort);
			_socket.setSoTimeout(20000);
			_outToSlave = new PrintStream(_socket.getOutputStream());
			_inFromSlave = new DataInputStream(this._socket.getInputStream());
			isConnected = true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("Can't connect socket!");
			e.printStackTrace();
			isConnected = false;
		}

	}

	public MasterConnector(Socket socket) {
		this._socket = socket;
		try {
			_outToSlave = new PrintStream(_socket.getOutputStream());
			_inFromSlave = new DataInputStream(this._socket.getInputStream());
			isConnected = true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("socket null!!!!!!!!!!!!");
			e.printStackTrace();
			isConnected = false;
			// return new MasterConnector();
		}
	}

	public String getRequest_XS(String request) {
		if (isConnected) {
			try {
				byte[] outMsg = null;
				int i = 0;
				try {
					outMsg = new byte[request.getBytes("UTF-8").length + 2];

					for (i = 0; i < request.getBytes("UTF-8").length; i++) {
						outMsg[i] = request.getBytes("UTF-8")[i];
					}
					outMsg[outMsg.length - 2] = (byte) 13;
					outMsg[outMsg.length - 1] = (byte) 10;
				} catch (UnsupportedEncodingException ex) {
					// ex.printStackTrace();
					stopConn2Master();
				}

				if (outMsg != null) {
					try {
						System.out.println("======>Send request:" + request);
						_outToSlave.write(outMsg);
						_outToSlave.flush();
					} catch (IOException ex) {
						// ex.printStackTrace();
						stopConn2Master();
					}
				}
				boolean running = true;
				byte[] buff = null;
				int buffLength;
				int bs, end;
				long time = 0;
				int delay = 3500;
				String strResult = "";
				while (running) {

					while (_inFromSlave.available() > 0) {
						bs = _inFromSlave.available(); // get the amount of
						buff = new byte[bs];
						buffLength = buff.length;
						_inFromSlave.read(buff, 0, buffLength);
						strResult = strResult + new String(buff);
					}
					Util.sleep(delay);
					time += delay;
					if (Util.isSMSReceiveTimeout(time)) {
						System.out.println("===>Time out");
						return null;
					}
					if (buff != null) {
						String[] str = strResult.split("\\|");
						System.out.println("===>DATA OK:" + strResult);
						running = false;
					}
				}
				if (!strResult.equals("")) {
					return strResult;
				} else
					return null;

			} catch (Exception e) {
				// TODO Auto-generated catch block
				return null;
			}
		} else
			return null;
	}

	public String getRequest(String request) {
		if (isConnected) {
			try {
				byte[] outMsg = null;
				int i = 0;
				try {
					outMsg = new byte[request.getBytes("UTF-8").length + 2];

					for (i = 0; i < request.getBytes("UTF-8").length; i++) {
						outMsg[i] = request.getBytes("UTF-8")[i];
					}
					outMsg[outMsg.length - 2] = (byte) 13;
					outMsg[outMsg.length - 1] = (byte) 10;
				} catch (UnsupportedEncodingException ex) {
					// ex.printStackTrace();
					stopConn2Master();
				}

				if (outMsg != null) {
					try {
						System.out.println("======>Send request:" + request);
						_outToSlave.write(outMsg);
						_outToSlave.flush();
					} catch (IOException ex) {
						// ex.printStackTrace();
						stopConn2Master();
					}
				}
				boolean running = true;
				byte[] buff = null;
				int buffLength;
				int bs, end;
				long time = 0;
				int delay = 300;
				String strResult = "";
				while (running) {

					while (_inFromSlave.available() > 0) {
						bs = _inFromSlave.available(); // get the amount of
						buff = new byte[bs];
						buffLength = buff.length;
						_inFromSlave.read(buff, 0, buffLength);
						// System.out.println("===> Server Response:" + new
						// String(buff));
						strResult = strResult + new String(buff);
					}
					Util.sleep(delay);
					time += delay;
					if (Util.isSMSReceiveTimeout(time)) {
						System.out.println("===>Time out");
						return null;
					}
					if (buff != null) {
						// return strResult;
						String[] str = strResult.split("\\|");

						// if (name.equals(str[0])) {
						System.out.println("===>DATA OK:" + strResult);
						running = false;
						// } else {
						// System.out.println("===>data no:" + strResult);
						// strResult = "";
						// buff=null;
						// }
					}
				}
				if (!strResult.equals("")) {
					return strResult;
				} else
					return null;

			} catch (Exception e) {
				// TODO Auto-generated catch block
				return null;
			}
		} else
			return null;
	}

	public String getRequest_Cau(String request) {
		System.out.println("RUN day 1");
		if (isConnected) {
			System.out.println("RUN day 2");
			try {
				byte[] outMsg = null;
				int i = 0;
				try {
					outMsg = new byte[request.getBytes("UTF-8").length + 2];

					for (i = 0; i < request.getBytes("UTF-8").length; i++) {
						outMsg[i] = request.getBytes("UTF-8")[i];
					}
					outMsg[outMsg.length - 2] = (byte) 13;
					outMsg[outMsg.length - 1] = (byte) 10;
				} catch (UnsupportedEncodingException ex) {
					// ex.printStackTrace();
					stopConn2Master();
				}

				if (outMsg != null) {
					try {
						System.out.println("======>Send request:" + request);
						_outToSlave.write(outMsg);
						_outToSlave.flush();
					} catch (IOException ex) {
						// ex.printStackTrace();
						stopConn2Master();
					}
				}
				boolean running = true;
				byte[] buff = null;
				int buffLength;
				int bs, end;
				long time = 0;
				int delay = 1000;
				String strResult = "";
				while (running) {

					while (_inFromSlave.available() > 0) {
						bs = _inFromSlave.available(); // get the amount of
						buff = new byte[bs];
						buffLength = buff.length;
						_inFromSlave.read(buff, 0, buffLength);
						// System.out.println("===> Server Response:" + new
						// String(buff));
						strResult = strResult + new String(buff);
					}
					Util.sleep(delay);
					time += delay;
					if (Util.isSMSReceiveTimeout(time)) {
						System.out.println("===>Time out");
						return null;
					}
					if (buff != null) {
						// return strResult;
						String[] str = strResult.split("\\|");

						// if (name.equals(str[0])) {
						System.out.println("===>DATA OK:" + strResult);
						running = false;
						// } else {
						// System.out.println("===>data no:" + strResult);
						// strResult = "";
						// buff=null;
						// }
					}
				}
				if (!strResult.equals("")) {
					return strResult;
				} else
					return null;

			} catch (Exception e) {
				// TODO Auto-generated catch block
				return null;
			}
		} else
			return null;
	}

	public boolean connect() {
		// có chỉnh sửa
		if (isConnected)
			return true;
		else
			return false;
	}

	public void closeConn(String request) {
		try {
			System.out.println("========>Close Connect");
			OutputStream _os = _socket.getOutputStream();
			PrintWriter out = new PrintWriter(_os, true);

			out.println(request);
			_socket = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			_socket = null;

		}

	}

	public void stopConn2Master() {
		// if (_socket != null) {
		// System.out.println("Stop Connect....");
		// try {
		// _socket.close();
		// _socket = null;
		// if (_outToSlave != null) {
		// _outToSlave.close();
		// }
		// if (_inFromSlave != null) {
		// _inFromSlave.close();
		// }
		// } catch (IOException ex) {
		// }
		// }
		// Runtime.getRuntime().gc();
	}

	public Socket get_socket() {
		return _socket;
	}

	public void set_socket(Socket socket) {
		_socket = socket;
	}

	public void sendRequest(String request) {
		byte[] outMsg = null;

		int i;
		try {
			outMsg = new byte[request.getBytes("UTF-8").length + 2];

			for (i = 0; i < request.getBytes("UTF-8").length; i++) {
				outMsg[i] = request.getBytes("UTF-8")[i];
			}
			outMsg[outMsg.length - 2] = (byte) 13;
			outMsg[outMsg.length - 1] = (byte) 10;
		} catch (UnsupportedEncodingException ex) {
			// ex.printStackTrace();
			stopConn2Master();
		}

		if (outMsg != null) {
			try {
				System.out.println("======>Send request");
				_outToSlave.write(outMsg);
				_outToSlave.flush();
			} catch (IOException ex) {
				// ex.printStackTrace();
				stopConn2Master();
			}
		}
	}

	public boolean checkJson(String json) {
		try {
			JSONObject jobject = new JSONObject(json);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}
